package com.yuandian.management.service.impl;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuandian.api.management.entity.ConfSystem;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.bpm.common.security.util.SecurityUtils;
import com.yuandian.management.mapper.ExcelBatchMapper;
import com.yuandian.management.mapper.ExcelBusinessMapper;
import com.yuandian.management.mapper.ExcelStepMapper;
import com.yuandian.management.service.ConfBusinessService;
import com.yuandian.management.service.ConfSystemService;
import com.yuandian.management.service.IExcelBatchService;
import com.yuandian.management.utils.ExcelBatchUtil;
import com.yuandian.management.vo.*;
import com.yuandian.utils.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;


/**
 * 导入流水service
 *
 * @author fucx
 * @date 2020/08/28
 */
@Service("excelBatchService")
public class ExcelBatchServiceImpl implements IExcelBatchService {

	@Autowired
	private ExcelBatchMapper excelBatchMapper;

	@Autowired
	private ConfSystemService confSystemService;

	@Autowired
	private ConfBusinessService confBusinessService;

	@Autowired
	private ExcelStepMapper excelStepMapper;

	@Autowired
	private ExcelBusinessMapper excelBusinessMapper;


	private static final String YES_FLAG = "是";
    private static final String NO_FLAG = "否";

	/**
	 * 查询流水信息
	 *
	 * @param params
	 * @return
	 */
	@Override
	public Page<ImportInfoVo> queryBatchList(ImportInfoVo params) {
		Page<ImportInfoVo> page = new Page<>(params.getPageNum(), params.getPageSize());
		Page<ImportInfoVo> infoVoPage = excelBatchMapper.queryPageByTime(page,params);
		infoVoPage.getRecords().forEach(importInfoVo -> {
			importInfoVo.setCreateTime(importInfoVo.getCreateTime().replace(".0",""));
		});
		return infoVoPage;
	}

	/**
	 * 导出Excel
	 *
	 * @param excelName  Excel表名
	 * @param dataNumber 流水号
	 * @param response
	 * @throws IOException
	 */
	@Override
	public void getExcelExport(String excelName, String dataNumber, HttpServletResponse response) throws IOException {
		Class[] clazz = {ExcelBusinessVo.class, ExcelStepVo.class };
		String[] sheetNames = {"业务" ,"步骤" };
		List<ExcelBusinessVo>  excelBusinessVoinessSteplist = excelBatchMapper.queryBusinessByDataNumber(dataNumber);
		List<ExcelStepVo> excelStepExportVos = excelStepMapper.queryStepByDataNumber(dataNumber);
		excelBusinessVoinessSteplist.forEach(e ->e.setBusinessStatus(Objects.equals(e.getBusinessStatus() ,"0")  == true ? "成功":"失败"));
		excelStepExportVos.forEach(e ->e.setDealStatus(Objects.equals(e.getDealStatus(),"0") == true ? "成功":"失败"));
		List[] datalist = {excelBusinessVoinessSteplist,excelStepExportVos};
		ExcelBatchUtil.writeExcel(clazz,response,excelName,sheetNames,datalist);
	}

	/**
	 * 导出Excel模板
	 *
	 * @param excelName Excel  表名
	 * @param filePath  模板Excel 存放的路径
	 * @param response
	 * @throws Exception
	 */
	@Override
	public void getTemplate(String excelName, String filePath, HttpServletResponse response) throws Exception {
		response.reset();
		response.setHeader("content-type", "application/octet-stream");
		String fileName = URLEncoder.encode(excelName, "utf-8").replaceAll("\\+", "%20");
		response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");
		ServletOutputStream out = null;
		FileInputStream input = null;
		ClassPathResource classPathResource=new ClassPathResource(filePath);
		InputStream inputStream = classPathResource.getInputStream();
		File file=File.createTempFile(fileName,".xlsx");
		FileUtils.copyInputStreamToFile(inputStream,file);
		try {

			input = new FileInputStream(file);
			out = response.getOutputStream();
			byte[] b = new byte[2048];
			int len;
			while ((len = input.read(b)) != -1) {
				out.write(b, 0, len);
			}
			//修正 Excel在“xxx.xlsx”中发现不可读取的内容。是否恢复此工作薄的内容？如果信任此工作簿的来源，请点击"是"
			response.setHeader("Content-Length", String.valueOf(input.getChannel().size()));
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
				}
			}
		}
	}

	/**
	 * 导入模板
	 *
	 * @param excelBusinessVoList 业务对象列表
	 * @param excelStepList       步骤对象列表
	 * @return
	 */
	@Override
	public R resultMap(List<ExcelBusinessVo> excelBusinessVoList, List<ExcelStepVo> excelStepList) {
		R result = new R();
		// 如果没有业务数据或者导入数量大于1000条提示
		// 预先处理如果步骤对应的业务序号不存在，那么直接返回
		result = isExcelDataValid(excelBusinessVoList,excelStepList);

		if (result.getCode() != 0) {
			return result;
		} else {
			importFile(excelBusinessVoList,excelStepList);
			result.setMsg("保存成功！");
		}

		return result;
	}

	/**
	 * 前端查询，根据流水号获取业务
	 * dataNumber: 流水号
	 * pageSize: 页大小
	 * pageNUm: 页号
	 *
	 * @param business
	 * @return
	 */
	@Override
	public Page<ExcelBusiness> queryBusinessBatchList(ImportBusinessResultVo business) {
		return null;
	}

	@Override
	public Page<ImportStepResultVo> queryStepList(ImportStepResultVo step) {
		Page<ImportStepResultVo> page = new Page<>(step.getPageNum(), step.getPageSize());
		return excelStepMapper.queryStepList(page, step);
	}


	/**
	 * 初步校验Excel表
	 * @param excelBusinessVoList
	 * @param excelStepList
	 * @return
	 */
	private R isExcelDataValid(List < ExcelBusinessVo > excelBusinessVoList, List < ExcelStepVo > excelStepList){


		if (excelBusinessVoList == null || excelBusinessVoList.size() < 1) {
			return R.failed("没有业务数据!");
		}

		if (excelBusinessVoList.size() > 1000) {
			return R.failed( "导入的业务不能大于1000条!");
		}

		if (excelStepList != null && excelStepList.size() > 1000) {
			return R.failed(4001, "导入的步骤不能大于1000条!");
		}

		//判断excel表中是否有相同的业务名称，相同则不允许导入
		List<String> businessNames=new ArrayList<>();
		for (ExcelBusinessVo excelBusinessVo:excelBusinessVoList) {
			if (businessNames.contains(excelBusinessVo.getSystemName()+"@"+excelBusinessVo.getBusinessName())){
				return R.failed( "业务不能重复，请修改业务名称!");
			}else{
				businessNames.add(excelBusinessVo.getSystemName()+"@"+excelBusinessVo.getBusinessName());
			}
		}

		//判断excel表中的业务名称在系统的业务中是否有相同，相同则不允许导入

		//1、根据系统名称查询出系统id；2、根据系统id查询出业务名称，步骤数量（类型）、如果excel表中的业务的步骤数量与
		//原系统的步骤数量不相同，且选择覆盖业务，则报错，不允许导入（存在同业务名称不同步骤数量，
		// 覆盖业务失败，请到业务配置修改对应的业务的步骤数量）
		for (ExcelBusinessVo excelBusinessVo:excelBusinessVoList) {
			if ("是".equals(excelBusinessVo.getCoverFlag())) {
				SystemManagementVo systemManagementVo = new SystemManagementVo();
				if (StringUtils.isBlank(excelBusinessVo.getSystemName())) {
					return R.failed( "excel表中系统名称不能为空!");
				}
				systemManagementVo.setName(excelBusinessVo.getSystemName());
				LambdaQueryWrapper<ConfSystem> wrapper = Wrappers.lambdaQuery();
				wrapper.eq(ConfSystem::getName, excelBusinessVo.getSystemName());

				List<ConfSystem> list = confSystemService.list(wrapper);
				if (list.size() > 0) {

				} else {
					return R.failed("该业务对应的系统不存在！");
				}
			}
		}



		List<String> bList = new ArrayList<String>();

		Map<String, String> sequenceNumberMap = new HashMap<>();
		for (ExcelBusinessVo excelBusinessVo : excelBusinessVoList) {
			String sequenceNumber = excelBusinessVo.getSequenceNumber() == null ? "" : excelBusinessVo.getSequenceNumber().trim();
			if (StringUtils.isNotBlank(sequenceNumber)) {
				if (bList.contains(sequenceNumber)) {
					return R.failed("有配置相同的业务序号：" + sequenceNumber + " ，请检查！");
				}

				bList.add(sequenceNumber);

				sequenceNumberMap.put(sequenceNumber, sequenceNumber);
			}else {
				return R.failed(excelBusinessVo.getBusinessName()+"的业务序号不能为空，请检查！");
			}
		}


		// 如果用户只更新业务，那么不对步骤业务序号不存在再处理了
		if (excelStepList == null || excelStepList.size() < 1) {
			return R.ok();
		}

		StringBuilder sb = new StringBuilder();
		List<String> list = new ArrayList<String>();

		for (ExcelStepVo excelStepVo : excelStepList) {
			String sequenceNumber = excelStepVo.getSequenceNumber() == null ? "" : excelStepVo.getSequenceNumber().trim();
			if (sequenceNumberMap.get(sequenceNumber) == null) {
				if (!list.contains(sequenceNumber)) {
					list.add(sequenceNumber);
				}
			}
		}

		if (list.size() > 0) {
			for (String sequenceNumber : list) {
				if (StringUtils.isNotBlank(sb.toString())) {
					sb.append(" , ");
					sb.append(sequenceNumber);
				} else {
					sb.append(sequenceNumber);
				}
			}
		}

		if (list.size() > 0) {
			return R.failed("导入的步骤列表，业务序号：" + sb.toString() + " 找不到对应的业务，请检查！");
		}


		//判断excel表中相同业务的步骤名称是否相同，相同则返回错误
		List<String> stepNames=new ArrayList<>();
		for (ExcelStepVo excelStepVo:excelStepList) {
			if (stepNames.contains(excelStepVo.getSequenceNumber()+"@"+excelStepVo.getStepName())){
				return R.failed("步骤不能重复，请修改步骤名称!");
			}else{
				stepNames.add(excelStepVo.getSequenceNumber()+"@"+excelStepVo.getStepName());
			}
		}

		//判断excel表中的相同业务下的步骤名称在系统的步骤列表中是否存在，存在则不能导入
		/**
		 * 1、先根据步骤数据的序号找到业务名称，系统名称，查询出步骤数据
		 */


		return R.ok();
	}

	/**
	 * 解析导入的Excel表信息
	 * @param excelBusinessVoList
	 * @param excelStepVoList
	 */
	private void importFile(List<ExcelBusinessVo> excelBusinessVoList, List<ExcelStepVo> excelStepVoList) {
		String dataNumber = getDataNumber();
		saveBatch(dataNumber, getUserName());
		// 处理后的业务列表
		List<ExcelBusiness> ebList = new ArrayList<ExcelBusiness>();

		List<List<ExcelBusiness>> excelBusList = new ArrayList<List<ExcelBusiness>>();

		List<List<ExcelStep>> excelStepList = new ArrayList<List<ExcelStep>>();

		// 第一步：把excel里面的业务和步骤数据，循环解析然后插入到数据库的导入表里面。
		// 1、分批插入业务数据到导入业务表。
		// 2、分批插入步骤数据到导入步骤表。
		if (excelBusinessVoList != null && excelBusinessVoList.size() > 0) {

			List<ExcelBusiness> ebusList = new ArrayList<ExcelBusiness>();

			List<ExcelBusinessVo> bList = excelBusinessVoList;

			for (ExcelBusinessVo bvo : bList) {
				ExcelBusiness eb = coverBusiness(bvo, getUserName(), dataNumber);
				ebList.add(eb);

				if (!ebusList.contains(eb)) {
					ebusList.add(eb);
				}
				// 批量业务插入表
				int ebusCount = ebusList.size() % 200;
				if (ebusCount == 0) {
					excelBusList.add(ebusList);
					ebusList = new ArrayList<ExcelBusiness>();
				}
			}

			if (ebusList.size() > 0) {
				excelBusList.add(ebusList);
			}

			List<ExcelStep> eStepList = new ArrayList<ExcelStep>();

			// 处理后的步骤列表
			List<ExcelStep> esList = new ArrayList<ExcelStep>();
			if (excelStepVoList != null && excelStepVoList.size() > 0) {
				List<ExcelStepVo> slist = excelStepVoList;
				for (ExcelStepVo svo : slist) {
					ExcelStep es = coverStep(svo,getUserName(), dataNumber);
					esList.add(es);

					if (!eStepList.contains(es)) {
						eStepList.add(es);
					}

					// 批量插入步骤
					int stepCount = eStepList.size() % 200;
					if (stepCount == 0) {
						excelStepList.add(eStepList);
						eStepList = new ArrayList<ExcelStep>();
					}

				}

				// 未满200的或者多余的
				if (eStepList.size() > 0) {
					excelStepList.add(eStepList);
				}

			}

			saveExcelBusiness(excelBusList);
			saveExcelStep(excelStepList);


		}
	}


	/**
	 *
	 * @param excelStepVo
	 * @param userName
	 * @param dataNumber
	 * @return
	 */
	private ExcelStep coverStep(ExcelStepVo excelStepVo, String userName, String dataNumber) {
		StringBuilder reason = new StringBuilder();

		int dealStatus = 0;
		ExcelStep es = new ExcelStep();
		es.setDataNumber(dataNumber);

		es.setSequenceNumber(excelStepVo.getSequenceNumber() == null ? "" : excelStepVo.getSequenceNumber().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getSequenceNumber())) {
			reason.append("业务序号不能为空！");
			dealStatus = 1;
		} else if (excelStepVo.getSequenceNumber().trim().length() > 10) {
			reason.append("业务序号大于10位，请按顺序填写！");
			dealStatus = 1;
			// 截取15位存放
			if (excelStepVo.getSequenceNumber().trim().length() > 15) {
				es.setSequenceNumber(excelStepVo.getSequenceNumber().trim().substring(0, 15));
			}
		} else if (!StringUtils.isNumeric(excelStepVo.getSequenceNumber())) {
			reason.append("业务序号不是数字！");
			dealStatus = 1;
		}

		es.setStepName(excelStepVo.getStepName() == null ? "" : excelStepVo.getStepName().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getStepName())) {
			reason.append("步骤名称不能为空！");
			dealStatus = 1;
		}
		else if (excelStepVo.getStepName().trim().length() > 200) {
			reason.append("步骤名称长度大于200！");
			dealStatus = 1;
			// 截取60位存放
			if (excelStepVo.getStepName().trim().length() > 60) {
				es.setStepName(excelStepVo.getStepName().trim().substring(0, 60));
			}
		}

		es.setStepType(excelStepVo.getStepType() == null ? "" : excelStepVo.getStepType().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getStepType())) {
			reason.append("步骤类型不能为空！");
			dealStatus = 1;
		} else if (excelStepVo.getStepType().trim().length() > 4) {
			reason.append("步骤类型只能填写：首步骤、末步骤、中间步骤！");
			dealStatus = 1;
			// 截取10位存放
			if (excelStepVo.getStepType().trim().length() > 10) {
				es.setStepType(excelStepVo.getStepType().trim().substring(0, 10));
			}
		} else if (!"首步骤".equals(excelStepVo.getStepType().trim()) && !"末步骤".equals(excelStepVo.getStepType().trim())
				&& !"中间步骤".equals(excelStepVo.getStepType().trim())) {
			reason.append("步骤类型只能填写：首步骤、末步骤、中间步骤！");
			dealStatus = 1;
		}

		es.setSequence(excelStepVo.getSequence() == null ? "" : excelStepVo.getSequence().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getSequence())) {
			reason.append("步骤顺序不能为空！");
			dealStatus = 1;
		} else {
			if (excelStepVo.getSequence().trim().length() > 10) {
				reason.append("步骤顺序超过10位 !");
				dealStatus = 1;

				if (excelStepVo.getSequence().trim().length() > 15) {
					es.setSequence(excelStepVo.getSequence().trim().substring(0, 15));
				}
			} else if (!StringUtils.isNumeric(excelStepVo.getSequence())) {
				reason.append("步骤顺序必须是数字！");
				dealStatus = 1;
			}
		}


		es.setIsAllowFail(excelStepVo.getIsAllowFail() == null ? "" : excelStepVo.getIsAllowFail().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getIsAllowFail())) {
			reason.append("是否允许失败不能为空！");
			dealStatus = 1;
		} else if (excelStepVo.getIsAllowFail().trim().length() > 2) {
			reason.append("是否允许失败，只能填是或者否！");
			dealStatus = 1;
			// 截取5位存放
			if (excelStepVo.getIsAllowFail().trim().length() > 5) {
				es.setIsAllowFail(excelStepVo.getIsAllowFail().trim().substring(0, 5));
			}
		} else if (!YES_FLAG.equals(excelStepVo.getIsAllowFail().trim()) && !NO_FLAG.equals(excelStepVo.getIsAllowFail().trim())) {
			reason.append("是否允许失败，只能填是或者否！");
			dealStatus = 1;
		}

		es.setIsAllowLose(excelStepVo.getIsAllowLose() == null ? "" : excelStepVo.getIsAllowLose().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getIsAllowLose())) {
			reason.append("是否可缺失不能为空！");
			dealStatus = 1;
		} else if (excelStepVo.getIsAllowLose().trim().length() > 2) {
			reason.append("是否可缺失，只能填是或者否！");
			dealStatus = 1;
			// 截取5位存放
			if (excelStepVo.getIsAllowLose().trim().length() > 5) {
				es.setIsAllowLose(excelStepVo.getIsAllowLose().trim().substring(0, 5));
			}
		} else if (!YES_FLAG.equals(excelStepVo.getIsAllowLose().trim()) && !NO_FLAG.equals(excelStepVo.getIsAllowLose().trim())) {
			reason.append("是否可缺失，只能填是或者否！");
			dealStatus = 1;
		}


		es.setConfirmFlag(excelStepVo.getConfirmFlag() == null ? "" : excelStepVo.getConfirmFlag().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getConfirmFlag())) {
			reason.append("是否确认不能为空！");
			dealStatus = 1;
		} else if (excelStepVo.getConfirmFlag().trim().length() > 2) {
			reason.append("是否确认，只能填是或者否！");
			dealStatus = 1;
			// 截取5位存放
			if (excelStepVo.getConfirmFlag().trim().length() > 5) {
				es.setConfirmFlag(excelStepVo.getConfirmFlag().trim().substring(0, 5));
			}
		} else if (!YES_FLAG.equals(excelStepVo.getConfirmFlag().trim()) && !NO_FLAG.equals(excelStepVo.getConfirmFlag().trim())) {
			reason.append("是否确认，只能填是或者否！");
			dealStatus = 1;
		}

		es.setResource(excelStepVo.getResource() == null ? "" : excelStepVo.getResource().trim());
		if (!StringUtils.isNotBlank(excelStepVo.getResource())) {
			reason.append("业务资源不能为空！");
			dealStatus = 1;
		}

		Date now = new Date();
		if (dealStatus == 1) {
			es.setDealStatus(dealStatus);
		}
		es.setReason(reason.toString());
		es.setTaskStatus(0);
		es.setStatus(0);
		es.setCreateBy(userName);
		es.setCreateTime(now);
		es.setUpdateBy(userName);
		es.setUpdateTime(now);

		return es;
	}


	/**
	 * 插入步骤信息
	 * @param excelStepList
	 */
	private void saveExcelStep (List < List < ExcelStep >> excelStepList) {
		if (excelStepList != null && excelStepList.size() > 0) {
			for (List<ExcelStep> list : excelStepList) {
				excelStepMapper.addAll(list);
			}
		}
	}


	/**
	 * 批量插入业务信息
	 * @param excelBusList
	 */
	private void saveExcelBusiness(List<List<ExcelBusiness>> excelBusList) {
		if (excelBusList != null && excelBusList.size() > 0) {
			for (List<ExcelBusiness> list : excelBusList) {
				excelBusinessMapper.addAll(list);
			}
		}
	}





	private ExcelBusiness coverBusiness(ExcelBusinessVo excelBusinessVo,String userName, String dataNumber){
		StringBuilder reason = new StringBuilder();

		int businessStatus = 0;

		ExcelBusiness eb = new ExcelBusiness();
		eb.setDataNumber(dataNumber);

		eb.setSequenceNumber(excelBusinessVo.getSequenceNumber() == null ? "" : excelBusinessVo.getSequenceNumber().trim());
		if (!StringUtils.isNotBlank(excelBusinessVo.getSequenceNumber())) {
			reason.append("业务序号不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getSequenceNumber().trim().length() > 10) {
			reason.append("业务序号大于10位，请按顺序填写！");
			businessStatus = 1;
			// 截取15位存放
			if (excelBusinessVo.getSequenceNumber().trim().length() > 15) {
				eb.setSequenceNumber(excelBusinessVo.getSequenceNumber().trim().substring(0, 15));
			}
		} else if (!StringUtils.isNumeric(excelBusinessVo.getSequenceNumber())) {
			reason.append("业务序号不是数字！");
			businessStatus = 1;
		}

		eb.setSystemName(excelBusinessVo.getSystemName() == null ? "" : excelBusinessVo.getSystemName().trim());
		if (!StringUtils.isNotBlank(excelBusinessVo.getSystemName())) {
			reason.append("系统名称不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getSystemName().trim().length() > 50) {
			reason.append("系统名称长度大于50！");
			businessStatus = 1;
			// 截取60位存放
			if (excelBusinessVo.getSystemName().trim().length() > 60) {
				eb.setSystemName(excelBusinessVo.getSystemName().trim().substring(0, 60));
			}
		}

		eb.setBusinessName(excelBusinessVo.getBusinessName() == null ? "" : excelBusinessVo.getBusinessName());
		if (!StringUtils.isNotBlank(excelBusinessVo.getBusinessName())) {
			reason.append("业务名称不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getBusinessName().trim().length() > 200) {
			reason.append("业务名称长度大于200！");
			businessStatus = 1;
			// 截取200位存放
			if (excelBusinessVo.getBusinessName().trim().length() > 200) {
				eb.setBusinessName(excelBusinessVo.getBusinessName().trim().substring(0, 200));
			}
		}

		eb.setKeyBusiness(excelBusinessVo.getKeyBusiness() == null ? "" : excelBusinessVo.getKeyBusiness().trim());
		if (!StringUtils.isNotBlank(excelBusinessVo.getKeyBusiness())) {
			reason.append("是否关键业务不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getKeyBusiness().trim().length() > 2) {
			reason.append("是否关键业务，只能填是或者否！");
			businessStatus = 1;
			// 截取5位存放
			if (excelBusinessVo.getKeyBusiness().trim().length() > 5) {
				eb.setKeyBusiness(excelBusinessVo.getKeyBusiness().trim().substring(0, 5));
			}
		} else if (!YES_FLAG.equals(excelBusinessVo.getKeyBusiness().trim()) && !NO_FLAG.equals(excelBusinessVo.getKeyBusiness().trim())) {
			reason.append("是否关键业务，只能填是或者否！");
			businessStatus = 1;
		}

		eb.setConfirmFlag(excelBusinessVo.getConfirmFlag() == null ? "" : excelBusinessVo.getConfirmFlag());
		if (!StringUtils.isNotBlank(excelBusinessVo.getConfirmFlag())) {
			reason.append("是否确认不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getConfirmFlag().trim().length() > 2) {
			reason.append("是否确认，只能填是或者否！");
			businessStatus = 1;
			// 截取5位存放
			if (excelBusinessVo.getConfirmFlag().trim().length() > 5) {
				eb.setConfirmFlag(excelBusinessVo.getConfirmFlag().trim().substring(0, 5));
			}
		} else if (!YES_FLAG.equals(excelBusinessVo.getConfirmFlag().trim()) && !NO_FLAG.equals(excelBusinessVo.getConfirmFlag().trim())) {
			reason.append("是否确认，只能填是或者否！");
			businessStatus = 1;
		}

		eb.setCoverFlag(excelBusinessVo.getCoverFlag() == null ? "" : excelBusinessVo.getCoverFlag().trim());
		if (!StringUtils.isNotBlank(excelBusinessVo.getCoverFlag())) {
			reason.append("是否覆盖不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getCoverFlag().trim().length() > 2) {
			reason.append("是否覆盖，只能填是或者否！");
			businessStatus = 1;
			// 截取5位存放
			if (excelBusinessVo.getCoverFlag().trim().length() > 5) {
				eb.setCoverFlag(excelBusinessVo.getCoverFlag().trim().substring(0, 5));
			}
		} else if (!YES_FLAG.equals(excelBusinessVo.getCoverFlag().trim()) && !NO_FLAG.equals(excelBusinessVo.getCoverFlag().trim())) {
			reason.append("是否覆盖，只能填是或者否！");
			businessStatus = 1;
		}

		eb.setClearStep(excelBusinessVo.getClearStep() == null ? "" : excelBusinessVo.getClearStep().trim());
		if (!StringUtils.isNotBlank(excelBusinessVo.getClearStep())) {
			reason.append("是否清空步骤不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getClearStep().trim().length() > 2) {
			reason.append("是否清空步骤，只能填是或者否！");
			businessStatus = 1;
			// 截取5位存放
			if (excelBusinessVo.getClearStep().trim().length() > 5) {
				eb.setClearStep(excelBusinessVo.getClearStep().trim().substring(0, 5));
			}
		} else if (!YES_FLAG.equals(excelBusinessVo.getClearStep().trim()) && !NO_FLAG.equals(excelBusinessVo.getClearStep().trim())) {
			reason.append("是否清空步骤，只能填是或者否！");
			businessStatus = 1;
		}

		eb.setStepNum(excelBusinessVo.getStepNum() == null ? "" : excelBusinessVo.getStepNum().trim());
		if (!StringUtils.isNotBlank(excelBusinessVo.getStepNum())) {
			reason.append("步骤类型不能为空！");
			businessStatus = 1;
		} else if (excelBusinessVo.getStepNum().trim().length() > 2) {
			reason.append("步骤类型请填写：1步、2步或者多步 !");
			businessStatus = 1;
			// 截取5位存放
			if (excelBusinessVo.getStepNum().trim().length() > 5) {
				eb.setStepNum(excelBusinessVo.getStepNum().trim().substring(0, 5));
			}
		} else if (!"1步".equals(excelBusinessVo.getStepNum().trim()) && !"2步".equals(excelBusinessVo.getStepNum().trim())
				&& !"多步".equals(excelBusinessVo.getStepNum().trim())) {
			reason.append("步骤类型请填写：1步、2步或者多步 !");
			businessStatus = 1;
		}

		eb.setShowOrder(excelBusinessVo.getShowOrder() == null ? "" : excelBusinessVo.getShowOrder().trim());
		if (StringUtils.isNotBlank(excelBusinessVo.getShowOrder())) {
			if (!StringUtils.isNumeric(excelBusinessVo.getShowOrder().trim())) {
				reason.append("显示顺序必须是数字！");
				businessStatus = 1;
			}

			if (excelBusinessVo.getShowOrder().trim().length() > 10) {
				reason.append("显示顺序超过10位 !");
				businessStatus = 1;

				if (excelBusinessVo.getShowOrder().trim().length() > 15) {
					eb.setShowOrder(excelBusinessVo.getShowOrder().trim().substring(0, 15));
				}
			}
		}

		// 如果选择的是1步：即首末步骤相同，要求url也相同。url允许都为空
       /* if ("1步".equals(eb.getStepNum()) && !eb.getBeginUrl().trim().equals(eb.getEndUrl().trim())) {
            reason.append("选择步骤数量1步，那么首末步骤URL必须相同!");
            businessStatus = 1;
        }*/

		Date now = new Date();

		if (businessStatus == 1) {
			eb.setBusinessStatus(businessStatus);
			eb.setStepStatus(1);
		}

		eb.setReason(reason.toString());
		eb.setTaskStatus(0);
		eb.setStatus(0);
		eb.setCreateBy(userName);
		eb.setCreateTime(now);
		eb.setUpdateBy(userName);
		eb.setUpdateTime(now);

		return eb;
	}


	/**
	 * 获取用户名
	 * @return
	 */
	private String getUserName () {
		return SecurityUtils.getUser().getName();
	}


	/**
	 * 保存流水信息
	 *
	 * @param dataNumber
	 * @param currentUser
	 */
	private void  saveBatch (String dataNumber, String currentUser){
		Date now = new Date();
		ExcelBatch eb = new ExcelBatch();
		eb.setDataNumber(dataNumber);
		eb.setTypeCode("excelBusinessVoinessStep");
		eb.setTypeName("业务步骤导入");
		eb.setDealStatus(0);
		eb.setDealTime(now);
		eb.setStatus(0);
		eb.setCreateBy(currentUser);
		eb.setCreateTime(now);
		eb.setUpdateBy(currentUser);
		eb.setUpdateTime(now);

		excelBatchMapper.save(eb);
	}

	/**
	 * 生成流水信息
	 * @return
	 */
	private String getDataNumber () {
//		Integer numberId = excelBatchMapper.queryDataNumberId();
//		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
//		String today = sdf.format(new Date());
//		String dataNumber = new StringBuffer().append(today).append(String.format("%05d", numberId)).toString();
		return String.valueOf(IdUtil.getSnowflakeNextId());
	}




}
